#include "StdAfx.h"
#include "WavFile.h"
#include "WaveSample.h"
#include <SFML/Audio/SoundFile.hpp>
#include <SFML/Audio/SoundBuffer.hpp>

//#include <sndfile.h>

WavFile::WavFile(void)
{
	sample = NULL;
}

WavFile::WavFile(const char* fileName, int channelCount, int rate, Sample* sample)
{
	if(fileName) 
	{
		this->fileName.assign(fileName);
	}
	this->channelCount = channelCount;
	this->rate = rate;
	this->sample = sample;
}

WavFile::~WavFile(void)
{
}

void WavFile::SaveToFile()
{
	sf::SoundBuffer* soundFile = new sf::SoundBuffer();
	soundFile->LoadFromSamples((const sf::Int16*)sample->data, sample->length, channelCount, rate);
	soundFile->SaveToFile(fileName);
	delete soundFile;
}

WavFile* WavFile::SaveToFile(const char* fileName, int channelCount, int rate, Sample* sample)
{
	WavFile* wavFile = new WavFile(fileName, channelCount, rate, sample);
	wavFile->SaveToFile();
	return wavFile;
}

WavFile* WavFile::LoadFromFile(const char* fileName)
{
	sf::SoundBuffer* soundFile = new sf::SoundBuffer();
	soundFile->LoadFromFile(fileName);
	WavFile* wavFile = new WavFile(fileName, soundFile->GetChannelsCount(), soundFile->GetSampleRate(), new Sample(soundFile->GetSamplesCount()));
	short* samples = (short*)soundFile->GetSamples();
	for(int i=0; i<wavFile->sample->length; i++)
	{
		wavFile->sample->data[i] = samples[i];
	}
	delete soundFile;
	return wavFile;
}